package com.example.aigc_education.integration.processor.v2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.integration.config.RestTemplateUtils;
import com.example.aigc_education.integration.constants.CozeConstant;
import com.example.aigc_education.integration.emuns.CozeAsyncWorkflow;
import com.example.aigc_education.integration.emuns.CozeWorkflowTypeV2;
import com.example.aigc_education.integration.processor.v1.async.CozeAsyncPlanRequest;
import com.example.aigc_education.integration.request.CozeRequest;
import com.example.aigc_education.integration.response.CozeAsyncResponse;
import com.example.aigc_education.integration.response.CozeResponse;
import com.example.aigc_education.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Optional;

/**
 * 异步工作流处理器
 * @param <T> 请求参数类型
 */
@Slf4j
public abstract class CozeAsyncProcessor<T> extends BaseCozeProcessor<T> {

    /**
     * 获取工作流类型
     * @return 工作流类型
     */
    public abstract CozeWorkflowTypeV2 workflowType();


    /**
     * 执行异步工作流
     * @param request 请求参数
     * @return 处理结果
     */
    public CozeResponse execute(CozeRequest<T> request) {
        if (!isParamValid(request)) {
            log.warn("参数校验失败: {}", JsonUtils.toJson(request));
            throw new BusinessException("参数校验失败");
        }
        try {
            request.setWorkflowId(workflowId());
            request.setAsync(true);

            JSONObject jsonObject = (JSONObject) JSON.toJSON(request);
            String url = CozeConstant.COZE_URL + "/workflow/run";

            String restResult = executeHttpRequest(url, jsonObject);
            log.info("异步工作流执行结果: {}", restResult);

            return JsonUtils.fromJson(restResult, CozeResponse.class);
        } catch (Exception e) {
            log.error("异步工作流执行异常", e);
            throw new BusinessException("执行异步工作流失败: " + e.getMessage());
        }
    }

    /**
     * 查询任务状态
     * @param executeId 执行ID
     * @return 任务状态
     */
    public CozeAsyncResponse queryTaskStatus(String executeId) {
        try {
            Map<String, String> headerMap = buildHeaders();
            String url = CozeConstant.COZE_URL + "/workflows/" + workflowId() + "/run_histories/" + executeId;

            log.info("查询任务状态: {}", url);
            String restResult = Optional.ofNullable(RestTemplateUtils.getHttp(url, null, headerMap))
                    .orElseThrow(() -> new BusinessException("查询任务状态失败"));

            log.info("任务状态查询结果: {}", restResult);
            return JsonUtils.fromJson(restResult, CozeAsyncResponse.class);
        } catch (Exception e) {
            log.error("查询任务状态异常", e);
            throw new BusinessException("查询任务状态失败: " + e.getMessage());
        }
    }
}
